package com.cloud.sky.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.cloud.sky.entity.bo.PageBO;
import com.cloud.sky.entity.bo.ResultBO;
import com.cloud.sky.entity.dto.*;
import com.cloud.sky.entity.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cloud.sky.component.HttpUtil.*;

/**
 * https://doc.apipost.net/docs/detail/2bed47b7c864000?target_id=2fb20d4
 * tingyukeji
 *
 * @author Tyrone
 * @date 2024/7/27 16:43
 */
@Component
@Slf4j
public class TingYuClient {


    private static String bigNodeListPath = "/jusha/v2/machine/all/list";
    private static String bigNodeDetailPath = "/jusha/v2/machine/all/";
    private static String bigNodeMonitorPath = "/jusha/v2/recentlogs";


    public static void main(String[] args) {
        TingYuClient tingYuClient = new TingYuClient();
        BigNodeListDTO bigNodeListDTO = new BigNodeListDTO();
        bigNodeListDTO.setSubName("w277361020");
        PageBO<BigNodeInfoVO> bigNodeInfoVOPageBO = tingYuClient.listBigNodeInfo(bigNodeListDTO);
        System.out.println(bigNodeInfoVOPageBO);
//        System.out.println(bigNodeInfoVOPageBO);
//        tingYuClient.getBigNodeInfoByUUID("10b638670cec7032de7679f092706d83");
//        tingYuClient.getBigNodeMonitor("10b638670cec7032de7679f092706d83", "20240701120000", "20240731120000");
//        PageBO<BoxInfoVO> boxList = tingYuClient.getBoxList(new BoxListQueryDTO());
//        SmallNodeDetailVO smallNodeDetail = tingYuClient.getSmallNodeDetail("arm-e91c29c27f1aa3c0df8123cfae3f0fdc", null);
//        System.out.println(smallNodeDetail);
//        System.out.println(boxList);
    }

    private Map<String, Object> convertObj2Map(Object obj) {
        String jsonString = JSON.toJSONString(obj);
        Map<String, Object> params = JSON.parseObject(jsonString, new TypeReference<Map<String, Object>>() {
        });
        return params;
    }

    /**
     * @param statusMapKey option 标记下机状态。normal：正常，offline：下机。不传显示全部，未来会扩展其他枚举值
     * @param uuid         option 资源UUID
     * @return
     */
    public PageBO<BigNodeInfoVO> listBigNodeInfo(BigNodeListDTO bigNodeListDTO) {
        try {
            Map<String, Object> params = convertObj2Map(bigNodeListDTO);
            String result = HttpUtil.call(bigNodeListPath, GET, params, null);
            ResultBO<PageBO<BigNodeInfoVO>> response = JSON.parseObject(result, new TypeReference<ResultBO<PageBO<BigNodeInfoVO>>>() {
            });
            return response.getData();
        } catch (Exception e) {
            log.error("com.cloud.sky.component.TingYuClient#listBigNodeInfo error:", e);

        }
        return null;
    }

    public BigNodeDetailVO getBigNodeInfoByUUID(String uuid) {
        try {

            String result = HttpUtil.call(bigNodeDetailPath + uuid, GET, null, null);
            ResultBO<BigNodeDetailVO> resultBO = JSON.parseObject(result, new TypeReference<ResultBO<BigNodeDetailVO>>() {
            });
            return resultBO == null ? null : resultBO.getData();
        } catch (Exception e) {
            log.error("com.cloud.sky.component.TingYuClient#getBigNodeIngoByUUID error:", e);
        }
        return null;
    }

    /**
     * @param uuid
     * @param startTime 20230913120000
     * @param endTime   20230913180000
     * @return
     */
    public List<BigNodeMonitorInfoVO> getBigNodeMonitor(String uuid, String startTime, String endTime) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("uuid", uuid);
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            String result = HttpUtil.call(bigNodeMonitorPath, GET, params, null);
            ResultBO<List<BigNodeMonitorInfoVO>> resultBO = JSON.parseObject(result, new TypeReference<ResultBO<List<BigNodeMonitorInfoVO>>>() {
            });
            return resultBO == null ? null : resultBO.getData();
        } catch (Exception e) {
            log.error("com.cloud.sky.component.TingYuClient#getBigNodeMonitor error:", e);
        }
        return null;
    }


    private static String smallNodeMonitorPath = "/jusha/v2/box/monitor";
    private static String smallNodeDetailPath = "/jusha/v2/box/detail";
    private static String smallNodeIncomeListPath = "/jusha/v2/box/daily/list";
    private static String smallNodeDailyIncomeDetailPath = "/jusha/v2/box/daily/";

    /**
     * @param uuid      uuid
     * @param startTime 2023-07-03 00:00:00
     * @param endTime   2023-08-01 23:59:59
     * @return
     */
    public SmallNodeMonitorInfoVO getSmallNodeMonitor(String uuid, String deviceId, String startTime, String endTime) {
        try {
            Map<String, Object> params = new HashMap<>();
            if (uuid != null) {
                params.put("uuid", uuid);
            }
            if (deviceId != null) {
                params.put("deviceId", deviceId);
            }
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            String result = HttpUtil.call(smallNodeMonitorPath, GET, params, null);
            ResultBO<SmallNodeMonitorInfoVO> smallNodeMonitorInfoVOResultBO = JSON.parseObject(result, new TypeReference<ResultBO<SmallNodeMonitorInfoVO>>() {
            });
            return smallNodeMonitorInfoVOResultBO == null ? null : smallNodeMonitorInfoVOResultBO.getData();
        } catch (Exception e) {
            log.error("com.cloud.sky.component.TingYuClient#getSmallNodeMonitor error:", e);
        }
        return null;
    }

    public SmallNodeDetailVO getSmallNodeDetail(String uuid, String deviceId) {
        try {
            Map<String, Object> params = new HashMap<>();
            if (uuid != null) {
                params.put("uuid", uuid);
            }
            if (deviceId != null) {
                params.put("deviceId", deviceId);
            }
            String result = HttpUtil.call(smallNodeDetailPath, GET, params, null);
            ResultBO<SmallNodeDetailVO> smallNodeDetailVOResultBO = JSON.parseObject(result, new TypeReference<ResultBO<SmallNodeDetailVO>>() {
            });
            return smallNodeDetailVOResultBO == null ? null : smallNodeDetailVOResultBO.getData();
        } catch (Exception e) {
            log.error("com.cloud.sky.component.TingYuClient#getSmallNodeDetail error:", e);
        }
        return null;
    }


    /**
     * @param subId     optional 子TP ID
     * @param uuid      optional 资源UUID
     * @param modelType optional 资源类型。仅可查看盒子与路由器，1 盒子， 2 路由器
     * @param startDate required 开始时间 20220801
     * @param endDate   required 结束时间 20220805
     * @return
     */
    public List<SmallNodeIncomeVO> getSmallNodeIncomeList(String subId, String uuid, String modelType, String startDate, String endDate) {
        try {
            Map<String, Object> params = new HashMap<>();
            if (subId != null) {
                params.put("subId", subId);
            }
            if (uuid != null) {
                params.put("uuid", uuid);
            }
            if (modelType != null) {
                params.put("modelType", modelType);
            }
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            String result = HttpUtil.call(smallNodeIncomeListPath, GET, params, null);
            ResultBO<List<SmallNodeIncomeVO>> listResultBO = JSON.parseObject(result, new TypeReference<ResultBO<List<SmallNodeIncomeVO>>>() {
            });
            return listResultBO == null ? null : listResultBO.getData();
        } catch (Exception e) {
            log.error("com.cloud.sky.component.TingYuClient#getSmallNodeIncomeList error:", e);
        }
        return null;
    }


    /**
     * @param uuid     资源uuid
     * @param deviceId 供应商设备ID,与UUID二选一
     * @param subId    子TP ID
     * @param date     2023-07-02
     * @return
     */
    public List<SmallDailyIncomeDetailVO> getSmallNodeDailyIncomeDetail(String uuid, String deviceId, String subId, String date) {
        try {
            Map<String, Object> params = new HashMap<>();
            if (uuid != null) {
                params.put("uuid", uuid);
            }
            if (deviceId != null) {
                params.put("deviceId", deviceId);
            }
            if (subId != null) {
                params.put("subId", subId);
            }
            String result = HttpUtil.call(smallNodeDailyIncomeDetailPath + date, GET, params, null);
            ResultBO<List<SmallDailyIncomeDetailVO>> listResultBO = JSON.parseObject(result, new TypeReference<ResultBO<List<SmallDailyIncomeDetailVO>>>() {
            });
            return listResultBO == null ? null : listResultBO.getData();
        } catch (Exception e) {
            log.error("com.cloud.sky.component.TingYuClient#getSmallNodeDailyIncomeDetail error:", e);
        }
        return null;
    }


    private static String boxListPath = "/jusha/v2/box/all/list";
    private static String forfeituresBoxListPath = "/jusha/v2/box/daily/forfeitures";
    private static String boxRemovePath = "/jusha/v2/box/remove";

    public PageBO<BoxInfoVO> getBoxList(BoxListQueryDTO dto) {
        try {
            Map<String, Object> params = convertObj2Map(dto);
            String result = HttpUtil.call(boxListPath, GET, params, null);
            ResultBO<PageBO<BoxInfoVO>> resultBO = JSON.parseObject(result, new TypeReference<ResultBO<PageBO<BoxInfoVO>>>() {
            });
            return resultBO == null ? null : resultBO.getData();
        } catch (Exception e) {
            log.error("com.cloud.sky.component.TingYuClient#getBoxList error:", e);
        }
        return null;
    }

    /**
     * @param uuid      deviceId 二选一
     * @param deviceId  uuid 二选一
     * @param subId     optional
     * @param startDate required 20230702
     * @param endDate   required 20230802
     * @return
     */
    public List<BoxForfeituresInfoVO> getForfeituresBoxList(String uuid, String deviceId, String subId, String startDate, String endDate) {
        try {
            Map<String, Object> params = new HashMap<>();
            if (uuid != null) {
                params.put("uuid", uuid);
            }
            if (deviceId != null) {
                params.put("deviceId", deviceId);
            }
            if (subId != null) {
                params.put("subId", subId);
            }
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            String result = HttpUtil.call(forfeituresBoxListPath, GET, params, null);
            ResultBO<List<BoxForfeituresInfoVO>> resultBO = JSON.parseObject(result, new TypeReference<ResultBO<List<BoxForfeituresInfoVO>>>() {
            });
            return resultBO == null ? null : resultBO.getData();
        } catch (Exception e) {
            log.error("com.cloud.sky.component.TingYuClient#getForfeituresBoxList error:", e);
        }
        return null;
    }

    /**
     * @param uuid     required
     * @param deviceId optional
     * @return
     */
    public ResultBO removeBox(String uuid, String deviceId) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("uuid", uuid);
            if (deviceId != null) {
                params.put("deviceId", deviceId);
            }
            String result = HttpUtil.call(boxRemovePath, DELETE, params, null);
            ResultBO resultBO = JSON.parseObject(result, ResultBO.class);
            return resultBO;
        } catch (Exception e) {
            log.error("com.cloud.sky.component.TingYuClient#removeBox error:", e);
            return buildExceptionBO(e);
        }
    }

    private static ResultBO buildExceptionBO(Exception e) {
        ResultBO resultBO = new ResultBO();
        resultBO.setSuccess(false);
        resultBO.setMessage(e.getMessage());
        return resultBO;
    }


    private static String routeBindPath = "/jusha/v2/router/bind";
    private static String routeWaitConnectNetListPath = "/jusha/v2/router/wait_distribution/list";
    private static String routeConnectedNetListPath = "/jusha/v2/router/all/list";

    public RouteBindInfoVO routeBind(RouteBindRequestDTO routeBindRequestDTO) {
        try {

            Map<String, Object> body = routeBindRequestDTO.convert2Map();
            String result = call(routeBindPath, POST, null, body);
            ResultBO<RouteBindInfoVO> routeBindInfoVOResultBO = JSON.parseObject(result, new TypeReference<ResultBO<RouteBindInfoVO>>() {
            });
            return routeBindInfoVOResultBO == null ? null : routeBindInfoVOResultBO.getData();
        } catch (Exception e) {
            log.error("com.cloud.sky.component.TingYuClient#routeBind error:", e);
        }
        return null;

    }

    /**
     * uuid
     * subId
     * page
     * size
     * both optional
     *
     * @param boxListQueryDTO
     * @return
     */
    public PageBO<RouteWaitConnectInfoVO> getRouteWaitConnectNetList(RouteListQueryDTO routeListQueryDTO) {
        try {
            Map<String, Object> param = convertObj2Map(routeListQueryDTO);
            String result = call(routeWaitConnectNetListPath, GET, param, null);
            ResultBO<PageBO<RouteWaitConnectInfoVO>> resultBO = JSON.parseObject(result, new TypeReference<ResultBO<PageBO<RouteWaitConnectInfoVO>>>() {
            });
            return resultBO == null ? null : resultBO.getData();
        } catch (Exception e) {
            log.error("com.cloud.sky.component.TingYuClient#getRouteWaitConnectNetList error:", e);
        }
        return null;
    }

    public PageBO<RouteConnectedInfoVO> getRouteConnectedNetList(RouteListQueryDTO routeListQueryDTO) {
        try {
            Map<String, Object> param = convertObj2Map(routeListQueryDTO);
            String result = call(routeConnectedNetListPath, GET, param, null);
            ResultBO<PageBO<RouteConnectedInfoVO>> resultBO = JSON.parseObject(result, new TypeReference<ResultBO<PageBO<RouteConnectedInfoVO>>>() {
            });
            return resultBO == null ? null : resultBO.getData();
        } catch (Exception e) {
            log.error("com.cloud.sky.component.TingYuClient#getRouteConnectedNetList error:", e);
        }
        return null;
    }

    private static String updateResourcePath = "/jusha/v2/resource/update/";

    public ResultBO updateResource(String uuid) {
        try {
            String result = call(updateResourcePath + uuid, GET, null, null);
            ResultBO resultBO = JSON.parseObject(result, new TypeReference<ResultBO>() {
            });
            return resultBO;
        } catch (Exception e) {
            log.error("com.cloud.sky.component.TingYuClient#updateResource error:", e);
            return buildExceptionBO(e);
        }
    }


    private static String getPriceConfigListPath = "/jusha/v2/machine/price/list";
    private static String resourcePricePath = "/jusha/v2/machine/price/list";
    private static String getResourceTrueFlowAndIncomePath = "/jusha/v2/daily/list";
    private static String getResourceDailyFlowAndIncomePath = "/jusha/v2/daily/";
    private static String getResourceEstimateFlowAndIncomePath = "/jusha/v2/daily/estimate/list";
    private static String getResourceEstimateDailyFlowAndIncomePath = "/jusha/v2/daily/estimate/";
    private static String getForfeituresPath = "/jusha/v2/daily/forfeitures";
    private static String getFeeCalculatePath = "/jusha/v2/resource/list";


    public PageBO<PriceConfigVO> getPriceConfigList(PriceConfigListDTO priceConfigListDTO) {
        try {
            Map<String, Object> params = convertObj2Map(priceConfigListDTO);
            String result = call(getPriceConfigListPath, GET, params, null);
            ResultBO<PageBO<PriceConfigVO>> bo = JSON.parseObject(result, new TypeReference<ResultBO<PageBO<PriceConfigVO>>>() {
            });
            return bo == null ? null : bo.getData();
        } catch (Exception e) {
            log.error("com.cloud.sky.component.TingYuClient#getPriceConfigList error:", e);

        }
        return null;
    }

    public ResourcePriceVO resourcePrice(ResourcePriceDTO dto) {
        try {
            Map<String, Object> params = convertObj2Map(dto);
            String result = call(resourcePricePath, PUT, null, params);
            ResultBO<ResourcePriceVO> bo = JSON.parseObject(result, new TypeReference<ResultBO<ResourcePriceVO>>() {
            });
            return bo == null ? null : bo.getData();
        } catch (Exception e) {
            log.error("com.cloud.sky.component.TingYuClient#resourcePrice error:", e);
        }
        return null;
    }

    public List<ResourceTrueFlowAndIncomeVO> getResourceTrueFlowAndIncome(ResourceTrueFlowAndIncomeDTO dto) {
        try {
            Map<String, Object> param = convertObj2Map(dto);
            String result = call(getResourceTrueFlowAndIncomePath, GET, param, null);
            ResultBO<List<ResourceTrueFlowAndIncomeVO>> bo = JSON.parseObject(result, new TypeReference<ResultBO<List<ResourceTrueFlowAndIncomeVO>>>() {
            });
            return bo == null ? null : bo.getData();
        } catch (Exception e) {
            log.error("com.cloud.sky.component.TingYuClient.getResourceTrueFlowAndIncome error:", e);
        }
        return null;
    }


}
